package com.lagou.edu.message.mq.listener;

import com.lagou.edu.common.constant.MQConstant;
import com.lagou.edu.common.mq.RocketMqService;
import com.lagou.edu.common.mq.dto.BaseMqDTO;
import com.lagou.edu.common.mq.listener.AbstractMqListener;
import com.lagou.edu.common.string.ValidateUtil;
import com.lagou.edu.common.util.ValidateUtils;
import com.lagou.edu.message.api.dto.CourseStatusReleaseDTO;
import com.lagou.edu.message.api.dto.LessonStatusReleaseDTO;
import com.lagou.edu.message.service.IMessageService;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.UUID;

@Slf4j
@Component
@RocketMQMessageListener(topic = MQConstant.Topic.COURSE_STATUS_RELEASE, consumerGroup = "${rocketmq.producer.group}" + "_" + MQConstant.Topic.COURSE_STATUS_RELEASE)
public class CourseStatusReleaseListener extends AbstractMqListener<BaseMqDTO<CourseStatusReleaseDTO>> implements RocketMQListener<BaseMqDTO<CourseStatusReleaseDTO>>{
	
    @Autowired
    private IMessageService messageService;

    @Autowired
    private RocketMqService rocketMqService;
	
    @Override
    public void onMessage(BaseMqDTO<CourseStatusReleaseDTO> data) {
        //校验参数
        ValidateUtils.notNullParam(data);
        ValidateUtils.notNullParam(data.getMessageId());

        if(this.checkMessageId(data.getMessageId())) {
            return;
        }
        //保存消息到消息表并获得要推送的用户
        List<Integer> userIdList = messageService.saveCourseMessage(data.getData().getCourseId());
        if(!Collections.isEmpty(userIdList)) {
            //发送消息准备推送给用户
            rocketMqService.convertAndSend(MQConstant.Topic.COURSE_RELEASE_SEND_MESSAGE, new BaseMqDTO<List<Integer>>(userIdList, UUID.randomUUID().toString()));
        }
        this.updateMessageId(data.getMessageId());
    }
}